package com.cxs;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/*
* @Project:spring-boot-shiro-demo
* @Author:cxs
* @Motto:放下杂念,只为迎接明天更好的自己
* */
@ControllerAdvice
public class ShiroExceptionHandler {

    /**
     * 处理用户认证时所抛出的异常
     * @param model
     * @param e
     * @return
     */
    @ExceptionHandler(value = AuthenticationException.class)
    public String authExceptionHandle(Model model, AuthenticationException e){
        if (e instanceof UnknownAccountException) {
            // 用户名不存在会抛出这个异常
            model.addAttribute("msg", "用户名不存在");
            return "error";
        } else if (e instanceof CredentialsException) {
            // 密码验证失败会抛出这个异常
            model.addAttribute("msg", "密码验证失败");
            return "error";
        } else {
            model.addAttribute("msg", "用户名或密码错误");
            return "error";
        }
    }

    /**
     * 处理授权时抛出的异常
     * @param model
     * @param e
     * @return
     * AuthorizationException 用户无权限访问资源会抛出这个异常
     */
    @ExceptionHandler(value = AuthorizationException.class)
    public String forbiddenExceptionHandle(Model model, AuthorizationException e){
        model.addAttribute("msg", "用户权限不足,拒绝访问");
        return "error";
    }
}
